/**
 * 滚动容器
 * @param page 页面对象
 * @param selector 容器选择器
 * @param totalSeconds 总秒数
 * @returns {Promise<*>}
 */
async function scrollContainer({page, selector, totalSeconds}) {
    console.log('总滚动时间：', totalSeconds)
    console.log('page:', page)

    return page.evaluate((selector, totalSeconds) => {
        return new Promise((resolve) => {
            const container = document.querySelector(selector);
            let top = 0;
            // 每 1000 毫秒滚动 2000px
            const timer = setInterval(() => {
                container.scrollTop = top += 2000;
                console.log('当前高度：', top);
            }, 1000);
            // 指定秒数后清除定时器并解决 Promise
            setTimeout(() => {
                clearInterval(timer);
                resolve();
            }, totalSeconds * 1000);
        });
    }, selector, totalSeconds);
}

async function scrollIntoView({page, selector, totalSeconds}) {
    console.log('总滚动时间：', totalSeconds)
    return page.evaluate((selector, totalSeconds) => {
        return new Promise((resolve) => {
            const container = document.querySelector(selector);
            const timer = setInterval(() => {
                container.scrollIntoView({
                    behavior:'smooth'
                });
            }, 1000);
            // 指定秒数后清除定时器并解决 Promise
            setTimeout(() => {
                clearInterval(timer);
                resolve();
            }, totalSeconds * 1000);
        });
    }, selector, totalSeconds);
}

module.exports = {
    scrollContainer,
    scrollIntoView
}

function giveALike(homePageId) {
    // 找到用户指定用户的评论
    let user = document.querySelector(`.comment-item-info-wrap a[href="//www.douyin.com/user/${homePageId}"]`)
    user.scrollIntoView({
        behavior:'smooth'
    });
    // 执行点赞动作
    user.closest('div[data-e2e="comment-item"]').querySelector('.xZhLomAs').click()
}
